# pip install akshare
import akshare as ak
import os
# pip install pyyaml
import time
from my_const import MY_PREFER_FUND_YML_LIST, HISTORY_DIR, HISTORY_SLEEP_TIME
from util.yml_util import read_fund_yml

from util.log_util import get_the_logger

logger = get_the_logger(__name__)

period = 'daily'


def read_funds_from_yml_list(yaml_file_list):
    all_fund_code_list = []
    all_code_to_name_map = {}

    for f in yaml_file_list:
        if not f.endswith('.yml') and not f.endswith('.yaml'):
            continue
        fund_code_list, code_to_name_map = read_funds_from_yml(f)

        for fund_code in fund_code_list:
            if fund_code not in all_code_to_name_map:
                all_fund_code_list.append(fund_code)
                all_code_to_name_map[fund_code] = code_to_name_map[fund_code]

    return all_fund_code_list, all_code_to_name_map


# not delete duplicated ones
def read_funds_from_yml(yaml_file):
    funds = read_fund_yml(yaml_file)
    fund_code_list = []
    code_to_name_map = {}
    if not funds:
        return [], {}
    for fund_info in funds.values():
        fund_code = fund_info['code']
        fund_name = fund_info['name']

        fund_code_list.append(fund_code)
        code_to_name_map[fund_code] = fund_name
    return fund_code_list, code_to_name_map


def read_funds_from_yml_dir(directory):
    fs = []
    for filename in os.listdir(directory):
        if filename.endswith('.yml') or filename.endswith('.yaml'):
            f = os.path.join(directory, filename)
            fs.append(f)
    return read_funds_from_yml_list(fs)


def update_list(fund_code_list, debug=False):
    for fund_code in fund_code_list:
        try:
            update_single(fund_code)
        except Exception as e:
            logger.error(f"{fund_code} not available by fund_open_fund: {e}")
            continue
        if not debug:
            time.sleep(HISTORY_SLEEP_TIME)


def update_single(fund_code):
    df = ak.fund_open_fund_info_em(symbol=fund_code, indicator="单位净值走势")
    if len(df) == 0:
        logger.info(f"Failed to fetch:{fund_code}")
    output_file_name = os.path.join(HISTORY_DIR, f'{fund_code}-{period}.csv')
    df.to_csv(output_file_name, index=False)
    logger.info(f"Succeed to fetch {fund_code}, save to {output_file_name}")


def get_fund_history_data(debug=False):
    # yaml_file = 'long_term.yml'
    # read fund from specific yml
    # fund_code_list, _ = read_funds_from_yml_list(LONG_TERM_FUND_YML_LIST)
    fund_code_list, _ = read_funds_from_yml_list(MY_PREFER_FUND_YML_LIST)

    # read all fund in input folder
    # fund_code_list, m = read_funds_from_yml_dir('input/')
    update_list(fund_code_list, debug)


if __name__ == '__main__':
    get_fund_history_data(debug=True)
